<?php
/**
 * Created on 2010-09-13
 *
 * @author 		micah <micah.shi@gmail.com>
 * @package 	protected.src
 */
abstract class BaseDao {
	/**
	 * @desc 获取数据库连接
	 * @return PDO
	 */
	abstract public function getConnection ();

	/**
	 * 获取表名
	 * @return string
	 */
	abstract public function getTableName ();

	protected function getWhereClause ($filters){
		if (null == $filters || count($filters) < 1 || !is_array($filters)) {
			return '';
		}
		$sqlClause = ' WHERE ';
		$filter_data = $filters[0];
		$filter_opt = $filters[1];
		if (null == $filter_data || count($filter_data) < 1 || null == $filter_opt || count($filter_opt) < 1) {
			return '';
		}
		foreach (array_keys($filter_data) as $key) {
			$opt = $filter_opt[$key];
			$sqlClause .= ' `' . $key . '`' . $opt . ':' . $key . ' AND ';
		}
		$resutStr = trim($sqlClause, ' AND ');
		return $resutStr;
	}

	protected function getBetweenClause ($filters){
		if (null == $filters || count($filters) < 1 || !is_array($filters)) {
			return '';
		}
		$sqlClause = ' WHERE ';
		$filter_data = $filters[0];
		$filter_opt = $filters[1];
		if (null == $filter_data || count($filter_data) < 1 || null == $filter_opt || count($filter_opt) < 1) {
			return '';
		}
		foreach (array_keys($filter_data) as $key) {
			$opt = $filter_opt[$key];
			$sqlClause .= ' `' . $key . '`' . $opt . ':' . $key . ' AND ';
		}
		$resutStr = trim($sqlClause, ' AND ');
		return $resutStr;
	}

	protected function getUpdateSetClause (array $fields){
		$updateSect = ' SET ';
		foreach (array_keys($fields) as $key) {
			$updateSect .= '`' . $key . '`=:' . $key . ',';
		}
		return substr_replace($updateSect, '', -1);
	}

	protected function getInsertClause (array $data){
		$fields = ' (';
		$values = ' VALUES (';
		foreach (array_keys($data) as $key) {
			$fields = $fields . '`' . $key . '`,';
			$values = $values . ':' . $key . ',';
		}
		$fields = substr_replace($fields, ')', -1);
		$values = substr_replace($values, ')', -1);

		return $fields . $values;
	}

	protected function bindValues ($stmt, $array) {
		foreach ($array as $key => $value) {
			$stmt->bindValue(':' . $key, $value);
		}
	}

	protected function bindValuesWithFilters ($stmt, $filters) {
		if (NULL != $filters && count($filters) > 0 && NULL != $filters[0] && count($filters[0]) > 0) {
			$this->bindValues($stmt, $filters[0]);
		}
	}

	public function setConnection ($conn){
		$this->connection = $conn;
	}
}
?>